package v3

import (
	"net/http"
)

type Server interface {
	Routable
	Start(address string) error
}

type sdkHttpServer struct {
	Name    string
	handler Handler
	root    Filter
}

func (s *sdkHttpServer) Route(method string, pattern string, handlerFunc func(c *Context)) {
	s.handler.Route(method, pattern, handlerFunc)
}

func (s *sdkHttpServer) Start(adder string) error {
	//http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
	//	c := NewContext(w, r)
	//	handlerFunc(c)
	//})

	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		s.root(NewContext(writer, request))
	})
	return http.ListenAndServe(adder, nil)
}

func NewSdkHttpServer(name string, builders ...FilterBuilder) Server {
	handler := NewHandlerBaseOnMap()

	var root Filter = func(c *Context) {
		handler.ServeHTTP(c)
	}
	for i := len(builders) - 1; i >= 0; i-- {
		b := builders[i]
		root = b(root)
	}

	res := &sdkHttpServer{
		Name:    name,
		handler: handler,
		root:    root,
	}
	return res
}
